package com.browser.core;

import javafx.scene.layout.BorderPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CompletableFuture;
import lombok.Data;
import javafx.concurrent.Worker;

@Data
public class BrowserTab {
    private static final Logger logger = LoggerFactory.getLogger(BrowserTab.class);
    
    private final BorderPane content;
    private final WebView webView;
    private final BrowserCore browserCore;
    private String currentUrl;
    private String title;

    public BrowserTab(BrowserCore browserCore) {
        this.browserCore = browserCore;
        this.content = new BorderPane();
        this.webView = new WebView();
        
        initializeTab();
        configureWebEngine();
    }

    private void configureWebEngine() {
        WebEngine engine = webView.getEngine();
        
        // 启用JavaScript
        engine.setJavaScriptEnabled(true);
        
        // 设置用户代理
        engine.setUserAgent("Mozilla/5.0 Simple-Browser");
        
        // 启用DOM存储
        engine.setUserDataDirectory(new java.io.File("browser-data"));
        
        // 配置自定义缓存策略
        engine.getLoadWorker().stateProperty().addListener((obs, oldState, newState) -> {
            if (newState == Worker.State.SUCCEEDED) {
                String url = engine.getLocation();
                if (url != null && !url.isEmpty()) {
                    // 将成功加载的页面内容存入缓存
                    try {
                        String content = (String) engine.executeScript(
                            "document.documentElement.outerHTML"
                        );
                        browserCore.getCacheManager().put(url, content);
                    } catch (Exception e) {
                        logger.warn("Failed to cache page content: {}", e.getMessage());
                    }
                }
            }
        });
    }

    private void initializeTab() {
        content.setCenter(webView);
        content.setUserData(this);
        
        // 监听URL变化
        webView.getEngine().locationProperty().addListener((obs, oldUrl, newUrl) -> {
            if (newUrl != null) {
                currentUrl = newUrl;
                browserCore.getHistoryManager().addEntry(newUrl, webView.getEngine().getTitle());
            }
        });

        // 监听标题变化
        webView.getEngine().titleProperty().addListener((obs, oldTitle, newTitle) -> {
            if (newTitle != null) {
                title = newTitle;
            }
        });

        webView.getEngine().getHistory().currentIndexProperty().addListener((obs, oldIndex, newIndex) -> {
            logger.debug("History index changed: {} -> {}", oldIndex, newIndex);
            // 当历史记录改变时，更新当前URL
            currentUrl = webView.getEngine().getLocation();
        });
    }

    public void loadUrl(String url) {
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            url = "http://" + url;
        }
        
        final String finalUrl = url;
        
        // 先检查缓存
        String cachedContent = browserCore.getCacheManager().get(finalUrl);
        if (cachedContent != null) {
            logger.info("Loading from cache: {}", finalUrl);
            webView.getEngine().loadContent(cachedContent);
            return;
        }

        // 异步加载内容
        browserCore.getNetworkManager().fetchContent(finalUrl)
            .thenAcceptAsync(content -> {
                // 缓存内容
                browserCore.getCacheManager().put(finalUrl, content);
                
                // 加载内容
                webView.getEngine().loadContent(content);
            }, javafx.application.Platform::runLater)
            .exceptionally(throwable -> {
                logger.error("Failed to fetch content: {}", finalUrl, throwable);
                return null;
            });

        // 同时开始直接加载URL（WebView有自己的缓存机制）
        logger.info("Loading URL: {}", finalUrl);
        webView.getEngine().load(finalUrl);
    }

    public void goBack() {
        try {
            if (webView.getEngine().getHistory().getCurrentIndex() > 0) {
                webView.getEngine().getHistory().go(-1);
            }
        } catch (Exception e) {
            logger.warn("Cannot go back: {}", e.getMessage());
        }
    }

    public void goForward() {
        try {
            if (webView.getEngine().getHistory().getCurrentIndex() < 
                webView.getEngine().getHistory().getEntries().size() - 1) {
                webView.getEngine().getHistory().go(1);
            }
        } catch (Exception e) {
            logger.warn("Cannot go forward: {}", e.getMessage());
        }
    }

    public void refresh() {
        webView.getEngine().reload();
    }

    public boolean canGoBack() {
        return webView.getEngine().getHistory().getCurrentIndex() > 0;
    }

    public boolean canGoForward() {
        return webView.getEngine().getHistory().getCurrentIndex() < 
               webView.getEngine().getHistory().getEntries().size() - 1;
    }
} 